﻿var appName = "OSharpApp";
angular.module(appName).controller("app.admin.identity.login", ["$scope", "$rootScope", "AUTH_EVENTS", "AuthService", function ($scope, $rootScope, AUTH_EVENTS, AuthService) {
    $rootScope.userLogined = false;
    $scope.loginInfo = {
        UserName: "",
        Password: "",
        VerifyCode: "",
        Remember: false
    };
    $scope.login = function (loginInfo) {
        AuthService.login(loginInfo).then(function (user) {
            console.log(user);
            $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
            $scope.setCurrentUser(user);
        }, function() {
            $rootScope.$broadcast(AUTH_EVENTS.loginFailed);
        });
    };
    $scope.verifyCode = {
        url: "/common/verify-code",
        refresh: function() {
            var num = new Date().getTime();
            this.url = "/common/verify-code?" + num;
        }
    };
    $scope.setCurrentUser = function(user) {
        console.info("set user");
    };
    $scope.$on("$includeContentLoaded", function() {
        if (!$rootScope.userLogined) {
            $("#modal-login").modal("show");
        }
    });
}]);
angular.module(appName).constant("AUTH_EVENTS", {
    loginSuccess: "auth-login-success",
    loginFailed: "auth-login-failed",
    logoutSuccess: "auth-logout-success",
    logoutFailed: "auth-logout-failed"
});
angular.module(appName).factory("AuthService", function($http, Session) {
    var authService = {};
    authService.login = function (loginInfo) {
        console.log("login called");
        return $http.post("/identity/login", loginInfo)
            .then(function(res) {
                var data = res.data;
                if (data.Type === "Success") {
                    console.info(data.Content);
                } else {
                    console.error(data.Content);
                }
                return data.Data;
            });
    }
    return authService;
});
angular.module(appName).service("Session", function() {
    this.create = function(sessionId, userId, userRole) {
        this.id = sessionId;
        this.userId = userId;
        this.userRole = userRole;
    };
    this.destroy = function() {
        this.id = null;
        this.userId = null;
        this.userRole = null;
    };
    return this;
});